package com.web.webstart.base.util;

import com.web.exiaodao.business.constant.JConstant;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.util.Properties;

public class FileUtil {
	//删除目录及目录下文件
	public static boolean deleteFiles(String filePath){
		boolean flag = false;
		File file = new File(filePath);
		File[] files = file.listFiles();
		for(int i = 0 ; i < files.length;i++){
			if(files[i].isFile()){
				flag = deleteFile(files[i].getAbsolutePath());
				if(!flag)break;
			}else{
				flag = deleteFiles(files[i].getAbsolutePath());
				if(!flag)break;
			}
		}
		return file.delete() ;
	}


	/**
	 * 创建一个Project临时目录
	 * windows:D:/template/projects/
	 * mac or linux:~/template/projects/
	 * @return
	 */
	public static String getProjectsPath() {
		String fileName = "";
		if (isWindos()) {
			fileName =  "D://template//projects//";
		}  else  {
			//   /users/username/template/projects
			String macUsrHome = System.getProperty("user.home");
			fileName =  macUsrHome + "/template/projects/";
		}
		File file = new File(fileName);
		try {
			file.mkdirs();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("***************文件目录创建失败,请手动创建***************" + e.getLocalizedMessage());
		}
		return fileName;
	}

	public static String getAlipaypayLogPath() {
		String filePath = "D:\\alipay_log\\" + JConstant.SERVER_NAME + "\\";
		if (!isWindos()) {
			filePath =  Thread.currentThread().getContextClassLoader().getResource("/" ).getPath();
			filePath = filePath + (filePath.endsWith(File.separator) ? "" : File.separator );
			filePath += "alipay_log";
		}
		return filePath;
	}

	/**
	 * 创建一个template临时目录
	 * windows:D:/template
	 * mac or linux:~/template
	 * @return
	 */
	public static String getTemplatePath() {
		String fileName = "";
		if (isWindos()) {
			fileName =  "D://template";
		}  else  {
			//   /users/username/template/projects
			String macUsrHome = System.getProperty("user.home");
			fileName =  macUsrHome + "/template";
		}
		File file = new File(fileName);
		try {
			file.mkdirs();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("***************文件目录创建失败,请手动创建2***************" + e.getLocalizedMessage());
		}
		return fileName;
	}

	public static boolean isWindos() {
		String osName = System.getProperty("os.name", "windows").toLowerCase();
		String fileName = "";
		if (osName.contains("windows")) {
			return true;
		}  else  {
			return false;
		}
	}

    /**
     * windows:\
     * linux or mac:/
     * @param path
     * @return
     */
	public static String dealPath(String path) {
	    if (XaUtil.isEmpty(path)) {
	        return "";
        }
        String sp = File.separator;
	    if (isWindos()) {
	    	sp = "\\";
		}
        path = path.replace("/", sp);
	    return path;
    }

	public static String readPropertiesFile(String key) {
		String fileName = "/filepath_win.properties";
		String filePath = "";
		InputStream inputStream = XaUtil.class.getResourceAsStream(fileName);
		Properties pros = new Properties();
		try {
			pros.load(inputStream);
			filePath = pros.getProperty(key);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return filePath;
	}

	/**
	 * 方法描述：将系统限定的路径转换为绝对正确的路径
	 *
	 * @param originalPath
	 * @return
	 */
	public static String getGeneralFilePath(String originalPath) {
		if ((null != originalPath) && !("".equals(originalPath))) {
			String strPath[] = originalPath.split("\\\\|/");
			originalPath = "";
			// 拼接jar路径
			for (int i = 0; i < strPath.length; i++) {
				if (!("".equals(strPath[i])) && !("".equals(strPath[i].trim()))) {
					originalPath = originalPath + strPath[i].trim();
					if (i < strPath.length - 1) {
						originalPath = originalPath + File.separator;
					}
				}
			}
		}
		return originalPath;
	}

	/**
	 * 往文件写数据
	 */
	public static void WriteFile(String content, String filePath,
								 String fileName) throws IOException {

		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		File f1 = new File(filePath + File.separator + fileName);
		FileUtils.writeStringToFile(f1, content, "utf-8");
	}

	/**
	 * 复制文件(以超快的速度复制文件)
	 *
	 * @param srcFile
	 *            源文件File
	 * //@param destDir
	 *            目标目录File
	 * //@param newFileName
	 *            新文件名
	 * @return 实际复制的字节数，如果文件、目录不存在、文件为null或者发生IO异常，返回-1
	 */
	@SuppressWarnings("resource")
	public static long copyFile(File srcFile, File destFile) throws Exception {
		long copySizes = 0;
		FileChannel fcin = new FileInputStream(srcFile).getChannel();
		FileChannel fcout = new FileOutputStream(destFile).getChannel();
		long size = fcin.size();
		fcin.transferTo(0, fcin.size(), fcout);
		fcin.close();
		fcout.close();
		copySizes = size;
		return copySizes;
	}

	/**
	 * 删除单个文件
	 *
	 * @param fileName
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.isFile() && file.exists()) {
			file.delete();
			//System.out.println("删除单个文件" + fileName + "成功！");
			return true;
		} else {
			//System.out.println("删除单个文件" + fileName + "失败！");
			return false;
		}
	}

	public static void makeDir(File dir) {
		if(! dir.getParentFile().exists()) {
			makeDir(dir.getParentFile());
		}
		dir.mkdir();
	}



	/**
	 *  Java 删除文件夹的办法
	 *  如果是空目录的话,可以直接删除成功,不是空目录要先递归删除子目录和文件
	 * @param path
	 */
	public static void deleteAllFilesOfDir(File path) {
		if (!path.exists())
			return;
		if (path.isFile()) {
			path.delete();
			return;
		}
		File[] files = path.listFiles();
		for (int i = 0; i < files.length; i++) {
			deleteAllFilesOfDir(files[i]);
		}
		path.delete();
	}


	/**
	 * 把字节数转化为kb或者mb
	 * @param bytes
	 * @return
	 */
	public static String bytes2kb(long bytes) {
		BigDecimal filesize = new BigDecimal(bytes);
		BigDecimal megabyte = new BigDecimal(1024 * 1024);
		float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
				.floatValue();
		if (returnValue > 1)
			return (returnValue + "MB");
		BigDecimal kilobyte = new BigDecimal(1024);
		returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
				.floatValue();
		return (returnValue + "KB");
	}

    public static void main(String[] args) {
        System.out.print(dealPath("/com/web/" + ""));
    }
}
